package com.xtt.executor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author ct
 * @description Executor多线程简单使用
 * @createTime 2017年4月25日 下午7:56:48
 */
public class ExecutorTest {
	private static ExecutorService executorService = Executors.newFixedThreadPool(10);
	private int pages = 1;
	private boolean running = true;
	public void task() {
		while(running) {
			if(pages < 100) {
				executorService.execute(new Runnable(){
					public void run() {
						System.out.println("爬取网页"+(pages++));
					}
				});
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				stop();
			}
		}
	}
	
	public static int getActiveCount() {
		ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor)executorService;
		return threadPoolExecutor.getActiveCount();
	}
	
	public void stop() {
		running = false;//停止执行线程
		if(getActiveCount() == 0) {//线程活动数量为0，关闭线程池
			executorService.shutdown();
		}
	}
	
	public static void main(String[] args) {
		ExecutorTest executor = new ExecutorTest();
		executor.task();
	}
}
